<?php

namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Illuminate\Http\Response;

use Closure;

class CrossRequestMiddleware
{
    private $headers;
    private $allowOrigin;

    public function handle(Request $request, Closure $next)
    {
        $this->headers = [
            'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE,OPTIONS',
            'Access-Control-Allow-Headers' => 'Origin,Accept,x-requested-with,content-type,xsrfCookieName,xsrfHeaderName,Cookie',
            'Access-Control-Allow-Credentials' => 'true',
            //'Content-type' => 'application/json;charset=utf-8'
        ];
        if ($request->isMethod('OPTIONS')) {
            $response = new Response('', 200);
            return $response;
        } else {
            $response = $next($request);
        }

        $this->allowOrigin = [
            'http://10.101.21.47:3000',
            'http://admin.jingying.com',
            'http://admin.jingying.com:3000',
            'http://wbzentao.wpt.la',
            'http://h5.student.com:8000',
            'http://h5.student.com',
            'https://h5.student.com',
            'https://h5.student.com:8001',
            'http://10.101.21.53',
            'http://10.101.21.41:3000',
            'https://mt.wpt.la',
            'http://mt.wpt.la',
            'https://qyt.wpt.la',
            'http://qyt.wpt.la',
            'https://localhost:8001',
            'http://127.0.0.1:3000',
            'http://localhost:3000',
            "https://qy.yingzhibowangluokeji.com",
            "http://qy.yingzhibowangluokeji.com",
            "https://m.yingzhibowangluokeji.com",
            "http://m.yingzhibowangluokeji.com",
            "http://sxs2-h5.weipaitang.com",
            "http://sxs2-admin.weipaitang.com",
            "http://sxs2-api.weipaitang.com",
            "https://sxs2-h5.weipaitang.com",
            "https://sxs2-admin.weipaitang.com",
            "https://sxs2-api.weipaitang.com"
        ];
        $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';


        if (!in_array($origin, $this->allowOrigin) && !empty($origin)) {
            return new Response('Forbidden', 403);
        }
        // if ($request->isMethod('options')) {return $this->setCorsHeaders(new Response('OK', 200), $origin);}

        $this->headers['Access-Control-Allow-Origin'] = $origin;
        foreach ($this->headers as $name => $value) {
            header($name . ': ' . $value);
        }

        return $response;
    }

    protected function setCorsHeaders(Response $response, $origin)
    {
        foreach ($this->headers as $key => $value) {
            $response->header($key, $value);
        }
        $response->header('Access-Control-Allow-Origin',
            in_array($origin, $this->allowOrigin) ? $origin : '');
        return $response;
    }
}